package com.itheima.Synchronized3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardId;
    private double money;

    //创建一个锁对象（实例变量：每个账户一个锁）
    //建议，设置成最终锁，不允许替换，一个账户锁对象是唯一的不能二次修改！
    private final Lock lock = new ReentrantLock();


    public void getmoney(double money) {
        Thread t = Thread.currentThread();
        try {
            lock.lock();
            System.out.println(t.getName() + "正在取钱：。。。。。");

            if (this.money >= money) {
                this.money -= money;
                System.out.println(t.getName() + "取钱成功！余额为：" + this.money);
            } else {
                System.out.println(t.getName() + "取钱失败！余额不足！");
            }
        } finally {
            lock.unlock();

        }
    }


    public Account() {
    }

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "cardId='" + cardId + '\'' +
                ", money=" + money +
                '}';
    }
}

